import React from 'react'
import { View, Image } from 'react-native'
import { Lt, Label, Color, Jx, Jpp, Navigator, Dialog } from "../_utils"
import { Overlay, AlbumView, Carousel } from '../_teaset';
import { Net, NET_GET, NET_ND, NET_NR, NET_RI } from "../_net"
// import jdFields from "./_jdFields.json";
import { eField, _eApp as eApp, eFieldTBTM } from './_efield';

export { eApp };


export const eSort = Object.freeze({
    none:0, up:1, down:2,

    fields : [
        ["综合", "佣金", "销量", "价格"], //拼多多
        ["综合", "佣金", "销量", "价格"], //淘宝
        ["综合", "佣金", "销量", "价格"], //京东
        ["综合", "佣金", "销量", "价格"], //天猫
    //  ["综合", "佣金", "销量", "价格"], //唯品会
    ],
    doubles : [
        3, //拼多多
        3, //淘宝
        3, //京东
        3, //天猫
    //  3, //唯品会
    ],
    defaultInfo : {index : 0},

})

// 各平台图标 样式
export const AppPorps = {
    style:{backgroundColor:Color.back},
    titleFontSize:Lt.c18,
    fields:eApp.idxs.map(v=>eApp.names[v]),
}
// 分类 样式
export const FieldProps = {
    justifyItem:"scrollable",
    titleFontSize:Lt.c16,
    itemStyle:{marginHorizontal:Lt.margin},
}

// const c_tbRand = "隐形眼镜\/护理液\/汽车\/用品\/配件\/改装\/家居饰品\/电子元器件\/男装\/住宅家具\/商业\/办公家具\/彩妆\/香水\/美妆工具\/美容护肤\/美体\/精油\/美发护发\/假发\/手机\/数码相机\/单反相机\/摄像机\/MP3\/MP4\/iPod\/录音笔\/笔记本\/平板电脑\/硬件\/显示器\/网络\/设备\/配件\/闪存卡\/U盘\/存储\/移动硬盘\/办公设备\/耗材\/电子词典\/电纸书\/文化用品\/电玩\/家电\/影音电器\/生活电器\/厨房电器\/个人护理\/保健\/按摩器材\/家装主材\/建材\/五金\/工具\/医疗\/健康\/电子\/电工\/摄像\/居家日用\/烹饪用具\/家庭\/个人清洁\/工具\/奶粉\/辅食\/营养品\/零食\/尿片\/洗护\/喂哺\/推车床\/孕妇装\/用品\/营养\/童装\/婴儿装\/亲子装\/滋补\/坚果\/特产\/粮油米面\/干货\/调味品\/数字\/运动\/瑜伽\/健身\/球迷\/户外\/登山\/野营\/旅行\/运动服\/休闲服装\/玩具\/童车\/益智\/积木\/模型\/箱包皮具\/热销女包\/男包\/女士内衣\/男士内衣\/家居服\/服饰配件\/皮带\/帽子\/围巾\/珠宝\/钻石\/翡翠\/黄金\/书籍\/杂志\/报纸\/乐器\/吉他\/钢琴\/运动鞋\/饰品\/流行首饰\/时尚饰品\/医疗器械\/计生用品\/洗护清洁剂\/卫生巾\/纸\/香薰\/咖啡\/麦片\/冲饮\/装修设计\/施工\/监理\/水产肉类\/新鲜蔬果\/熟食\/手表\/酒类\/童鞋\/婴儿鞋\/亲子鞋\/自行车\/骑行装备\/零配件\/家庭保健\/居家布艺\/节庆用品\/礼品\/餐饮具\/收纳整理\/品牌台机\/品牌一体机\/服务器\/电动车\/配件\/交通工具\/农用物资\/农机\/农具\/农膜\/畜牧\/养殖物资\/整车\/模玩\/动漫\/周边\/二手数码";
const c_tbRand = "用品\/家居饰品\/男装\/美妆\/美容护肤\/美发护发\/护理\/保健\/健康\/居家日用\/孕妇装\/童装\/婴儿装\/亲子装\/运动服\/休闲服装\/箱包皮具\/热销女包\/男包\/运动鞋\/流行首饰\/时尚饰品";
export class cHome{

    // 价格单位转换
    static toPrice(price, value){
        if(!price){
            return 0;
        }
        price = parseFloat(price / value).toFixed(2);
        if(price.endsWith(".00")){
            return parseInt(price);
        }else if(price.endsWith("0")){
            return price.substr(0, price.length - 1);
        }
        return price;
    }

    // 
    static toApp(istmall, appIdx){
        let app = Jx.isUndefined(appIdx) ? eApp.TB : eApp.idxs[appIdx];
        if(Jx.isString(istmall) && istmall != "false" && istmall != "FALSE" && istmall != "0"){
            app = eApp.TM;
        } else if(istmall && (app == eApp.TB || app == eApp.TM)){
            app = eApp.TM;
        }
        return app;
    }

    // 服务器商品数据转换到客户端
    static toDataInner(data, appIdx, priceValue){
        let newData = { ...data };
        const app = this.toApp(data.istmall, appIdx);
        newData.appIdx = eApp.rdxs[app];
        newData.zk_money = ((app == eApp.TB || app == eApp.TM) && !data.hasCoupon) ? 0 : this.toPrice(data.zk_money, priceValue);
        newData.zk_price = Jx.isUndefined(data.zk_price) ? 0 : this.toPrice(data.zk_price, priceValue);
        newData.price = this.toPrice(data.price, priceValue);
        // 京东Apps 原价和券后价一样
        if(newData.price == newData.zk_price){
            newData.price = parseFloat(newData.zk_price) + parseFloat(newData.zk_money);
        }
        newData.agent = this.toPrice(data.agent, priceValue);
        return newData;
    }

    // 服务器商品数据转换到客户端
    static toData(data, appIdx){
        return this.toDataInner(data, appIdx, 100);
    }

    // 服务器商品数据转换到客户端(首页轮播图图)
    static toDataForHomeBanner(data){
        return this.toDataInner(data, eApp.rdxs[eApp.TB], 1);
    }

    // 服务器商品数据转换到客户端(朋友圈)
    static toDataForMoments(data){
        return this.toDataInner(data, eApp.rdxs[eApp.TB], 1);
    }

    // static getTbRand(){
    //     // let names = tbFields.item_cats.item_cat.map(v=>v.name);
    //     // names = names[parseInt(Math.random() * names.length)];
    //     // console.log(names);
    //     // names = names.split("/");
    //     let names = c_tbRand.split("/");
    //     names = names[parseInt(Math.random() * names.length)];
    //     console.log(names);
    //     names = names[parseInt(Math.random() * names.length)];
    //     console.log(names);
    //     return names;
    // }

    // static getCatRand(){
    //     return "21,19,29,50016348,50026523,50025705,50010404,16,50002766,50008090";
    // }

    // static getJdRand(){
    //     let names = jdFields.data.map(v=>v.name);
    //     names = names[parseInt(Math.random() * names.length)];
    //     names = "服饰内衣/美妆护肤/运动户外/母婴/家居日用/礼品/文娱/本地生活/旅游出行/钟表";
    //     console.log(names);
    //     names = names.split("/");
    //     names = names[parseInt(Math.random() * names.length)];
    //     names = names[parseInt(Math.random() * names.length)];
    //     console.log(names);
    //     return names;
    // }

    // 转换分类信息
    static getCatCid(app, fieldIdx, forApps){
        const isTBTM = app == eApp.TB || app == eApp.TM;
        const id = (isTBTM && forApps) ? eFieldTBTM[fieldIdx].id : eField[app][fieldIdx].id;
        if(isTBTM){
            return id ? { tbcat : id } : {};
        }
        if(app == eApp.PDD){
            return { opt : id };
        }
        if(app == eApp.JD){
            return id ? { cid : id } : {};
        }
        return {};
    }

    // 转换排序信息
    static getSort(app, info){
        const index = info.index;
        if(app == eApp.TB || app == eApp.TM){
            if(index == 1){
                return { tbsort : "tk_ratet_des" }; // k_total_commi_des 
            }
            if(index == 2){
                return { tbsort : "total_sales_des" };
            }
            if(index == 3){
                return { tbsort : ((info.eud === eSort.down) ? "price_des" : "price_asc") };
            }
            return {};
        }
        if(app == eApp.JD){
            if(index == 1){
                return {jdsort:"commissionShare", jdorder:"desc"}; // commission
            }
            if(index == 2){
                return {jdsort:"inOrderCount30Days", jdorder:"desc"}; //inOrderComm30Days
            }
            if(index == 3){
                return (info.eud == eSort.down) ? {jdsort:"price", jdorder:"desc"} : {jdsort:"price", jdorder:"asc"};
            }
            return {};
        }
        if(app == eApp.PDD){
            if(index == 1){
                return { sort : 2 };
            }
            if(index == 2){
                return { sort : 6 };
            }
            if(index == 3){
                return { sort : ((info.eud == eSort.down) ? 4 : 3) };
            }
            return {};
        }
        return {};
        // 排序方式:
        // 0-综合排序;
        // 1-按佣金比率升序;
        // 2-按佣金比例降序;
        // 3-按价格升序;
        // 4-按价格降序;
        // 5-按销量升序;
        // 6-按销量降序;
        // 7-优惠券金额排序升序;
        // 8-优惠券金额排序降序;
        // 9-券后价升序排序;
        // 10-券后价降序排序;
        // 11-按照加入多多进宝时间升序;
        // 12-按照加入多多进宝时间降序;
        // 13-按佣金金额升序排序;
        // 14-按佣金金额降序排序;
        // 15-店铺描述评分升序;
        // 16-店铺描述评分降序;
        // 17-店铺物流评分升序;
        // 18-店铺物流评分降序;
        // 19-店铺服务评分升序;
        // 20-店铺服务评分降序;
        // 27-描述评分击败同类店铺百分比升序，
        // 28-描述评分击败同类店铺百分比降序，
        // 29-物流评分击败同类店铺百分比升序，
        // 30-物流评分击败同类店铺百分比降序，
        // 31-服务评分击败同类店铺百分比升序，
        // 32-服务评分击败同类店铺百分比降序
        // https://open.pinduoduo.com/#/apidocument/port?id=28
    }

    // 
    static toDevid(appIdx){
        let app = eApp.idxs[appIdx];
        if(app == eApp.PDD){
            app = 1;
        }else if(app == eApp.JD){
            app = 2;
        }else{
            app = 0;
        }
        return app;
    }

    static _fetImagesMap = new Map;
    static getImages(goodId){
        return this._fetImagesMap.get(goodId);
    }

    // 拼多多有些商品没有图片, 需要额外从详情信息获取图片组的第一张
    static fetImages(data, silent = true){
        return new Promise((resolve, reject)=>{
            // jdurl
            const url = "Shop/Detail?type=" + this.toDevid(data.appIdx) + "&goodId=" + data.goodId;
            Net.request(url, null, silent ? {NET_GET, NET_ND, NET_NR} : {NET_GET, NET_ND})
            .then(r=>{
                if(r.data){
                    let details = r.data.list;
                    if(details && details.length > 0){
                        this._fetImagesMap.set(data.goodId, details);
                        resolve(details);
                    }else{
                        reject(r);
                    }
                }else{
                    reject(r);
                }
            }).catch(err=>{
                reject(err);
            })
        })
    }

    // 判断是否在图片缓存中(上一个函数), 没有的话就向服务器请求
    static setImages(data, cbState){
        // 有details说明imgUrl就是details[0]
        let image = data.imgUrl || "";
        let images = [""];
        let details = data.details || [""];
        let needFet = true;
        if(data.details){
            images = details;
            needFet = false;
        }else {
            const ds = this.getImages(data.goodId);
            if(ds){
                details = ds;
                if(image){
                    images = [image].concat(ds);
                }else{
                    image = ds[0];
                    images = ds;
                }
                needFet = false;
            }
        }
        cbState(true, image, details, images);
        if(needFet){
            this.fetImages(data).then(ds=>{
                details = ds;
                if(image){
                    images = [image].concat(ds);
                }else{
                    image = ds[0];
                    images = ds;
                }
                cbState(false, image, details, images);
            }).catch(err=>{
                if(image){
                    cbState(false, image, [image], [image]);
                }
            })
        }
    }

    // 点击商品 跳到详情页
    static jump2detail(data){
        Navigator.push("GoodsDetail", { data });
    }

    // 给商品带上平台索引, 方便商品详情页 <为您推荐> 推荐同类型(相同的平台索引)商品
    static toFieldIdx(dataArr, fieldIdx){
        if(Jx.isArray(dataArr)){
            for(let k = dataArr.length - 1; k >= 0; --k){
                dataArr[k].fieldIdx = fieldIdx;
            }
        }
    }

    // 跳转领券/跳到分享 都要请求的推广信息(比如推广二维码，分享地址)
    static toConver(data, cbOk){
        return new Promise((resolve, reject)=>{
            const devId = this.toDevid(data.appIdx);
            if(!data.jdurl || !data.coupon){
                Net.request("other/convert", {devId, goodId:data.goodId}, {NET_RI}).then(r=>{
                    if(r.data){
                        cbOk && cbOk(r.data);
                        resolve(r.data);
                    }else{
                        reject(r);
                    }
                }).catch(err=>{
                    reject(err);
                })
                return;
            }
            const jdurl = encodeURIComponent(data.jdurl);
            const coupon = encodeURIComponent(data.coupon);
            Dialog.retain(true);
            fetch(Net._url +  "other/convert?devId="+devId+"&jdurl="+jdurl+"&coupon="+coupon, 
            { method:'POST', headers:{token:Net._token}})
            .then(r=>r.json()).then(r=>{
                Dialog.release();
                if(Net.isSuccess(r, "other/convert", true) && r.data){
                    cbOk && cbOk(r.data);
                    resolve(r.data);
                }else{
                    reject(r);
                }
            })
            .catch(err=>{
                Dialog.release();
                reject(err);
            })
            return;
            let uri = "http://coupon.jd.com/ilink/couponActiveFront/front_index.action?key=0899b63b3b7448369d0bf33c4dc612e5&roleId=18390801&to=item.jd.com/27925631116.html"
            console.log("encodeURI:   " + encodeURI(uri));
            console.log("decodeURI:   " + decodeURI(uri));
            console.log("encodeURIComponent:   " + encodeURIComponent(uri));
            console.log("decodeURIComponent:   " + decodeURIComponent(uri));
            console.log("escape:   " + escape(uri));
            console.log("unescape:   " + unescape(uri));
            console.log("decodeURIComponent(encodeURIComponent(encodeURIComponent)):   " + decodeURIComponent(encodeURIComponent(encodeURIComponent(uri))));
            let obj = { devId : cHome.toDevid(data.appIdx)} ;
            if(data.jdurl && data.coupon){
                console.log(data.coupon);
                obj.jdurl = encodeURIComponent(data.jdurl);
                obj.coupon = encodeURIComponent(data.coupon);
                console.log(obj.coupon);
            }else{
                obj.goodId = data.goodId;
            }
            Net.request("other/convert", obj, {NET_RI}).then(r=>{
                if(r.data){
                    this.convert = r.data;
                    resolve(r.data);
                }else{
                    reject(r);
                }
            }).catch(err=>{
                reject(err);
            })
        })
    }

    // 跳转第三方app需要的地址处理
    static toScheme(app, goodId, data){
        if(app == eApp.TB || app == eApp.TM){
            return String(data.uland_url).substr(8);
        }else if(app == eApp.JD){
            return "virtual?params={\"category\":\"jump\",\"des\":\"getCoupon\",\"url\":\"" + data.uland_url + "\"}";
            return "virtual?params={\"category\":\"jump\",\"des\":\"getCoupon\",\"skuId\":\"" + goodId + "\",\"url\":\"" + data.uland_url + "\"}";
            return "virtual?params={\"category\":\"jump\",\"des\":\"productDetail\",\"skuId\":\"" + 
            goodId + "\",\"sourceType\":\"JSHOP_SOURCE_TYPE\",\"sourceValue\":\"JSHOP_SOURCE_VALUE\"}";
        }else if(app == eApp.PDD && data.url){
            return String(data.url).substr(8);
        }
        return "";
    }

    // 点击轮播图，弹出相册浏览模式
    static onAlbum(onRef, props){
        const style = {width:10,height:10,borderRadius:5,margin:5,}
        let album = (
            <Overlay.PopView
                style={{backgroundColor:"white"}}
                containerStyle={{flex: 1}}
                overlayOpacity={1}
                ref={onRef}
            >
                <AlbumView
                    style={{flex: 1}}
                    control={<Carousel.Control
                        dot={<View style={{backgroundColor:"gray", ...style}}/>}
                        activeDot={<View style={{backgroundColor:Color.theme, ...style}}/>}
                    />}
                    {...props}
                />
                {/* <StatusBar hidden={true} /> */}
            </Overlay.PopView>
        );
        Overlay.show(album);
    }
}